<?php
/**
 * 登录控制器
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace ckeeper\http;

use ckeeper\db\Transaction;
use ckeeper\utils\ManagerActionRecorder;
use ckeeper\utils\PasswordEncrypt;
use ckeeper\dao\ManagerDao;
use Selibra\Di\Annotations\Autowired;
use Selibra\Di\Annotations\Component;
use Selibra\Http\Annotations\Controller;
use Selibra\Http\Annotations\Route;
use Selibra\Http\Lib\HttpController;
use Selibra\Tools\Console;

/**
 * 后台登录控制器
 * Class Login
 * @package Admin\Account
 */
#[Component]
#[Controller("/manage/system")]
class Login extends HttpController
{


    /**
     * @var ManagerDao
     */
    #[Autowired]
    protected ManagerDao $managerDao;


    /**
     * 执行后台登录
     * @return mixed
     */
    #[Route("/login")]
    public function execLogin()
    {
        $username = htmlspecialchars(trim($this->getRequest()->getPost('username')));
        $password = htmlspecialchars(trim($this->getRequest()->getPost('password')));
        if (empty($username) || empty($password)) {
            return $this->error("参数错误，请检查用户名密码.", [], 100);
        }
        // 获取账户信息
        $managerEntity = $this->managerDao->getManagerAccountByUsername($username);
        if (empty($managerEntity)) {
            return $this->error("账户不存在", [], 101);
        } elseif (!PasswordEncrypt::checking($password, $managerEntity->getPassword(), $managerEntity->getSalt())) {
            return $this->error("密码错误", [], 102);
        }

        // 执行登录步骤
        Transaction::begin();
        try {
            // 生成token
            $token = md5(uniqid());

            // 修改登录token
            $this->managerDao->updateLoginToken($managerEntity->getUuid(), $token);

            // 记录操作日志
            ManagerActionRecorder::info(
                $managerEntity->getUuid(),
                'login',
                '用户登录',
                $this->getRequest()
            );

            // 提交事务
            Transaction::commit();
        } catch (\Exception $exception) {
            Transaction::rollback();
            // 回退事务
            Console::log($exception);
            return $this->error("登录失败，失败原因请查看系统日志", [], 1);
        }
        return $this->success("登录成功", [
            'token' => $token,
        ]);
    }


    /**
     * 退出登录
     * @return mixed
     */
    #[Route("/logout")]
    public function logout()
    {
        return $this->success("退出登录成功");
    }

}
